#
# Copyright (c) 2023 supercell
#
# SPDX-License-Identifier: BSD-3-Clause
#

module Luce
  # Parses lines fenced with `>>>` to blockquotes
  class FencedBlockquoteSyntax < BlockSyntax
    def pattern : Regex
      Luce.blockquote_fence_pattern
    end

    def parse_child_lines(parser : BlockParser) : Array(Line)
      child_lines = [] of Line
      parser.advance

      until parser.done?
        match = pattern.matches? parser.current.content
        if match
          parser.advance
          break
        else
          child_lines << parser.current
          parser.advance
        end
      end

      child_lines
    end

    def parse(parser : BlockParser) : Node
      child_lines = parse_child_lines(parser).compact_map { |e| e }

      # Recursively parse the contents of the blockquotes
      children = BlockParser.new(child_lines, parser.document).parse_lines
      Element.new("blockquote", children)
    end
  end
end
